package com.zz.hhbl.ui.operationdemonstration

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.zz.framework.core.base.BaseFragment
import com.zz.framework.core.config.GlobalSetting
import com.zz.framework.core.ext.finish
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.utils.language.Strings
import com.zz.framework.widget.banner.Banner
import com.zz.framework.widget.banner.indicator.RectangleIndicator
import com.zz.framework.widget.banner.listener.OnPageChangeListener
import com.zz.hhbl.R
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.databinding.FragmentOperationDemonstrationBinding
import com.zz.hhbl.entity.SpotConfigEntity
import com.zz.hhbl.entity.SpotInfoEntity
import com.zz.hhbl.ui.CommonViewModel
import com.zz.hhbl.ui.MusicPlayerTestFragment
import com.zz.hhbl.ui.earphone.EarphoneChoiceFragment
import com.zz.hhbl.ui.operationdemonstration.banner.DemonstrationAdapter
import com.zz.hhbl.ui.operationdemonstration.banner.VideoHolder
import dagger.hilt.android.AndroidEntryPoint

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/20 11:56.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
@AndroidEntryPoint
class OperationDemonstrationFragment : BaseFragment(R.layout.fragment_operation_demonstration) {
    private val viewModel: CommonViewModel by viewModels()
    private val binding: FragmentOperationDemonstrationBinding? by viewBinding()

    override fun initView() {
        initBanner()
        binding?.btnNext?.apply {
            this.text = Strings.下一步.toLanguage()
            this.onClick {
                jumpToNextItem()
            }
        }
        binding?.btnSkip?.apply {
            this.onClick {
                jumpToEarphoneChoice()
            }
            this.text = Strings.跳过.toLanguage()
        }
    }


    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    override fun onResume() {
        super.onResume()
        GSYVideoManager.onResume(false)
    }

    override fun onDestroyView() {
        GSYVideoManager.releaseAllVideos()
        super.onDestroyView()
    }

    private fun initBanner() {
        var mBanner = (binding?.banner as? Banner<SpotConfigEntity, DemonstrationAdapter>)
        val list = GlobalCache.getSpotInfo().bootPageData
//        list.addAll(GlobalCache.getSpotInfo().bootPageData!!)
//        list.add(SpotConfigEntity(name = "xx", url = "http://14.103.144.167:9000/senlian/2025/02/20/测试_20250220154928A023.mp4", type = "video"))
        mBanner?.apply {
            setAdapter(
                DemonstrationAdapter(list)
            )
//            isAutoLoop(list.isNullOrEmpty().not())
            addBannerLifecycleObserver(getBaseActivity())
            setIndicator(RectangleIndicator(getBaseActivity()))
            addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                }

                override fun onPageSelected(position: Int) {
                    if (list.isNullOrEmpty().not()) {
                        startLoop()
                    }
                    //大于0说明有播放
                    val playPosition = GSYVideoManager.instance().playPosition
                    if (playPosition >= 0) {
                        //对应的播放列表TAG
                        if (GSYVideoManager.instance().playTag == VideoHolder.TAG && (position != playPosition)) {
                            GSYVideoManager.releaseAllVideos()
                            playPosition(position)
                        }
                    } else {
                        playPosition(position)
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
        }
    }


    private fun playPosition(position: Int) {
        binding?.banner?.postDelayed(Runnable {
            val viewHolder = (binding?.banner?.viewPager2?.getChildAt(0) as? RecyclerView)?.findViewHolderForAdapterPosition(position)
            if (viewHolder != null && viewHolder is VideoHolder) {
                // 设置不循环播放
                stoptLoop()
                val recyclerItemNormalHolder: VideoHolder = viewHolder as VideoHolder
                recyclerItemNormalHolder.gsyVideoPlayer.let {
                    it.startPlayLogic()
                    // 监听播放完成事件
                    it.setVideoAllCallBack(object : GSYSampleCallBack() {
                        override fun onComplete(url: String?, vararg objects: Any?) {
                            super.onComplete(url, *objects)
                            getBaseActivity()?.runOnUiThread {
                                startLoopImmediately()
                            }
                        }

                        override fun onAutoComplete(url: String?, vararg objects: Any?) {
                            super.onAutoComplete(url, *objects)
                            getBaseActivity()?.runOnUiThread {
                                startLoopImmediately()
                            }
                        }
                    })
                }
            }
        }, 50)
    }


    fun startLoop() {
//        binding?.banner?.let {
//            it.isAutoLoop(true)
//            it.start()
//        }
    }

    fun startLoopImmediately() {
//        binding?.banner?.let {
//            it.isAutoLoop(true)
//            it.startImmediately()
//        }
    }

    fun jumpToNextItem() {
        if (binding?.banner?.itemCount?:0<=1){
            jumpToEarphoneChoice()
        }else if (binding?.banner?.currentItem == binding?.banner?.itemCount?.minus(1)) {
            jumpToEarphoneChoice()
        }else{
            binding?.banner?.jumpToNextItem()
        }
    }

    private fun jumpToEarphoneChoice() {
        if (getIntent().getBooleanExtra("isBack", false).not()) {
            startParentActivity(EarphoneChoiceFragment::class.java)
        }
        finish()
    }

    fun stoptLoop() {
//        binding?.banner?.let {
//            it.isAutoLoop(false)
//            it.stop()
//        }
    }
}